package com.antwork.common.web.jsp;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;

public class SearchTag extends AbstractTag {
	private static final long serialVersionUID = 5103725520120949949L;
	private static HashMap<String, SearchConfig> configMap = new HashMap();
	private String name;

	public void setName(String name) {
		this.name = name;
	}

	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) this.pageContext
				.getRequest();
		String uri = (String) request.getAttribute("uri");
		String q = (String) request.getAttribute("q");
		String qt = (String) request.getAttribute("qt");
		q = (q == null) ? "" : q;
		qt = (qt == null) ? "" : qt;
		SearchConfig config = (SearchConfig) configMap.get(this.name);
		if (config == null) {
			try {
				config = loadConfig();
			} catch (Exception e) {
				throw new JspException(e);
			}
			configMap.put(this.name, config);
		}
		if (config == null) {
			return 6;
		}
		StringBuffer htmlStr = new StringBuffer("<form>");
		String[] queryType = config.getQueryType();
		if (queryType == null) {
			uri = setSearchForURI(uri);
			htmlStr.append("<div class=\"input-append\">");
			htmlStr.append("<input class=\"span2\" id=\"q\" style=\"width:100%\" type=\"text\" value=\""
					+ q + "\">");
			htmlStr.append("<button class=\"btn\" type=\"button\" onclick=\"query('"
					+ uri + "')\">" + config.getButtonName() + "</button>");
			htmlStr.append("</div>");
		} else {
			String[] displayName = config.getDisplayName();
			htmlStr.append("<div class=\"input-append\">");
			htmlStr.append("<input class=\"span2\" id=\"q\" style=\"width:100%\" type=\"text\" value=\""
					+ q + "\">");
			htmlStr.append("<div class=\"btn-group\">");
			htmlStr.append("<button class=\"btn dropdown-toggle\" data-toggle=\"dropdown\">"
					+ config.getButtonName()
					+ " <span class=\"caret\"></span></button>");
			htmlStr.append("<ul class=\"dropdown-menu\">");

			for (int i = 0; i < queryType.length; ++i) {
				String cls;
				if (qt.equals(queryType[i]))
					cls = " class=\"active\"";
				else {
					cls = "";
				}
				uri = setSearchGroupForURI(uri, queryType[i]);
				uri = setSearchForURI(uri);
				htmlStr.append("<li" + cls
						+ "><a href=\"###\" onclick=\"query('" + uri + "')\">"
						+ displayName[i] + "</a></li>");
			}
			htmlStr.append("</ul>");
			htmlStr.append("</div>");
			htmlStr.append("</div>");
		}
		htmlStr.append("</form>");
		JspWriter writer = this.pageContext.getOut();
		try {
			writer.write(htmlStr.toString());
		} catch (IOException e) {
			throw new JspException(e);
		}
		return 6;
	}

	private SearchConfig loadConfig() throws Exception {
		String configName = "/page-" + this.name + ".properties";
		Properties prop = new Properties();
		try {
			InputStream is = SearchTag.class.getResourceAsStream(configName);
			// Properties prop = new Properties();
			prop.load(is);
		} catch (Throwable e) {
			throw new RuntimeException("table-config file cannot be load: "
					+ configName);
		}
		try {
			// Properties prop = null;
			SearchConfig config = new SearchConfig();
			String buttonName = (String) prop.get("search.button");
			config.setButtonName(buttonName);
			String categoryStr = (String) prop.get("search.category");
			if (categoryStr != null) {
				String[] cs = categoryStr.split(";");
				String[] queryType = new String[cs.length];
				String[] displayName = new String[cs.length];
				for (int i = 0; i < cs.length; ++i) {
					String[] c = cs[i].split("\\|");
					queryType[i] = c[0];
					displayName[i] = c[1];
				}
				config.setQueryType(queryType);
				config.setDisplayName(displayName);
			}
			return config;
		} catch (Exception e) {
			throw new Exception("Parse " + configName + " error! "
					+ e.getMessage());
		}
	}

	private String setSearchForURI(String uri) {
		uri = uri.replace("###", "");

		int index = uri.indexOf("q=");
		String newURI;
		if (index != -1) {
			String s1 = uri.substring(0, index);
			String s2 = uri.substring(index, uri.length());
			String s3 = null;
			index = s2.indexOf("&");
			if (index != -1)
				s3 = s2.substring(index, s2.length());
			if (s3 != null)
				newURI = s1 + s3;
			else {
				newURI = s1;
			}
			newURI = newURI + "&q=";
			newURI = newURI.replace("?&", "?");
			newURI = newURI.replace("&&", "&");
		} else {
			if (uri.indexOf("?") != -1)
				newURI = uri + "&q=";
			else {
				newURI = uri + "?q=";
			}
		}
		return newURI;
	}

	private String setSearchGroupForURI(String uri, String qt) {
		int index = uri.indexOf("qt=");
		String newURI;
		if (index != -1) {
			String s1 = uri.substring(0, index);
			String s2 = uri.substring(index, uri.length());
			String s3 = null;
			index = s2.indexOf("&");
			if (index != -1)
				s3 = s2.substring(index, s2.length());
			if (s3 != null)
				newURI = s1 + "qt=" + qt + s3;
			else
				newURI = s1 + "qt=" + qt;
		} else {
			if (uri.indexOf("?") != -1)
				newURI = uri + "&qt=" + qt;
			else {
				newURI = uri + "?qt=" + qt;
			}
		}
		return newURI;
	}
}